/*---------------------------------------------------------------------------------------
 - FileName:ble_communication.h
 - Date:    2016-06-15 10:54:46
 - Author:  Liut
 - Instruction: app set beacon config data . ble communication.
----------------------------------------------------------------------------------------*/
#ifndef BLE_COMMUNICATION_H
#define BLE_COMMUNICATION_H
#include "stdint.h"
#include "m_ota.h"

#define     APP_TIMER_PRESCALER   0
#define     DFU_PACKET_TIMER_INTERVAL       APP_TIMER_TICKS(1000, APP_TIMER_PRESCALER)

#define     DFU_SINGLE_PACKET_TIMEOUT       (3)     //单包超时设置秒（超过这个时间没有收到过包）
#define     DFU_MODULE_TIMEOUT              (10)     //DFU模块超时设置秒

#define     BLE_PACKET_LENGTH_MAX           (1028+256)
#define     BLE_PACKET_MAGIC_HEAD           (0xbc)

#define PACKET_HEADER_SIZE  6
//dfu packet format
typedef struct
{
    uint8_t         magic_num;
    uint8_t         cmd;
    uint16_t        length;
    uint16_t        crc16;
    uint8_t         p_data[];
}packet_header_t;

//模块超时控制
typedef struct
{
    uint8_t on:1;       //on(1) off flag
    uint8_t timecont:7; //cout for time out.
}m_packet_timer_ctr_t;


//数据接收控制
typedef struct
{
    uint8_t     status;
    uint8_t     cmd;
    uint16_t    received_len; 
    uint16_t    packet_len;
    uint16_t    crc16;
    uint8_t     data_buffer[BLE_PACKET_LENGTH_MAX];    
}ble_packet_ctr_t;


void ble_communication_init(void);
void m_dfu_data_receive_handle(uint8_t *p_data, uint8_t len);
void m_dfu_ack_handle(m_ota_cmd_type_t cmd_type,m_ota_error_code_t result);
void m_ble_conn_update_handle(void);
void m_dfu_conn_disconnected_handle(void);
void ble_send_ack_result(uint8_t cmd, uint8_t result);
uint8_t m_dfu_if_going(void);
/**
 * @brief 先往data_buff里复制data区域，这里只是用来拼包及结构体
 * 
 * @param cmd 
 * @param length 
 */
void ble_communication_send_start(uint8_t cmd, uint16_t length);

/**
 * @brief 获取发送buff的data区的指针
 * 
 * @return uint8_t* 
 */
uint8_t* ble_communication_send_get_data_ptr(void);

uint8_t* ble_communication_get_data_ptr_end(void);

void ble_communication_send_set_data_ptr(uint8_t* buff);

void ble_communication_receive_clear(void);
#endif
